//
//  CPSCMarkAttributedStringTools.m
//  CollTest
//
//  Created by codew on 11/18/21.
//

#import "CPSCMarkAttributedStringTools.h"

#define KValueImageMarginTitle 4

@interface CPSCMarkAttributedStringTools ()

@property (nonatomic, strong) NSMutableDictionary * dictImage;

@end

@implementation CPSCMarkAttributedStringTools

+ (instancetype)shared {
    
    static CPSCMarkAttributedStringTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[CPSCMarkAttributedStringTools alloc] init];
        
        instance.dictImage = [NSMutableDictionary dictionary];
        
    });
    return instance;
}

+ (CGSize)sizeLabelToFit:(NSAttributedString *)aString
                   width:(CGFloat)width
                  height:(CGFloat)height
{
    
    
    UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    tempLabel.attributedText = aString;
    tempLabel.numberOfLines = 0;
    [tempLabel sizeToFit];
    CGSize size = tempLabel.frame.size;
    size = CGSizeMake(ceilf(size.width), ceilf(size.height));
    return size;
}

/**
 原价 中划线
 */
+ (NSAttributedString *)attributedStringOriginalPrice:(NSString *)price
                                           unitString:(NSString *)unitString
                                      lineContainUnit:(BOOL)lineContainUnit
{
    if (unitString.length < 1) {
        unitString = @"元";
    }
    price = [NSString stringWithFormat:@"%@%@", price, unitString];
        
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:price];
    NSRange strRange;// = {0,[str length] - unitString.length };
    if (lineContainUnit) {
        
        strRange = NSMakeRange(0, str.length);
    }else{
        strRange = NSMakeRange(0, [str length] - unitString.length);
         
    }
    
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:strRange];

    [str addAttribute:NSStrikethroughStyleAttributeName
                value:[NSNumber numberWithInteger:NSUnderlineStyleSingle]
                range:strRange];
    
    
        
    return str;
}

/**
 商品名字, 带"限时秒杀" 那种
 https://codesign.qq.com/s/7VXl9Or85mj8WRA/nGaV96pBpNZPqwd
 */
+ (NSMutableAttributedString *)attributedStringWithMarkImage:(UIImage *)image
                                          imageBounds:(CGRect)imageBounds
                                          contentText:(NSString *)contentText
                                            lineSpacingValue:(CGFloat)lineSpacingValue
{
    
    NSString *titleString = contentText;
    //创建  NSMutableAttributedString 富文本对象
    
//    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
//    paragraphStyle.lineSpacing = lineSpacingValue;
//    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//    [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    
    NSMutableAttributedString *maTitleString = [[NSMutableAttributedString alloc] initWithString:titleString];
    
    if ( !image ) {
        
        NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
        paragraphStyle.maximumLineHeight = 23;
        paragraphStyle.minimumLineHeight = 23;
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
        
        //
        [maTitleString addAttribute:NSParagraphStyleAttributeName
                              value:paragraphStyle
                              range:NSMakeRange(0,maTitleString.length)];
        return maTitleString;
    }
    
    
    
    //创建Image的富文本格式
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.bounds = imageBounds;
    attach.image = image;
    //添加到富文本对象里
    NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:attach];
    [maTitleString insertAttributedString:imageStr atIndex:0];//加入文字前面
    
    
//    //设置空格文本
//    [maTitleString insertAttributedString:[[NSAttributedString alloc] initWithString:@"_"] atIndex:1];
//    //设置间距
//    [maTitleString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:4] range:NSMakeRange(1,1)];
//    [maTitleString addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(1,1)];
//    [maTitleString addAttribute:NSKernAttributeName
//                          value:@(4)
//                          range:NSMakeRange(1,1)];
    
    //设置空格文本
    [maTitleString insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:1];
    [maTitleString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:4] range:NSMakeRange(1,1)];
    //设置间距
    [maTitleString addAttribute:NSKernAttributeName
                          value:@(2)
                          range:NSMakeRange(1,1)];
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.maximumLineHeight = 23;
    paragraphStyle.minimumLineHeight = 23;
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    
    //
    [maTitleString addAttribute:NSParagraphStyleAttributeName
                          value:paragraphStyle
                          range:NSMakeRange(0,maTitleString.length)];
//    NSInteger value = contentText.length;
//    NSInteger value2 = maTitleString.length;
    
    
    NSLog(@"");
    return maTitleString;
}

/**
 商品名字, 带"限时秒杀" 那种
 https://codesign.qq.com/s/7VXl9Or85mj8WRA/nGaV96pBpNZPqwd
 */
+ (NSAttributedString *)attributedStringWithMarkTitle:(NSString *)markTitle contentText:(NSString *)contentText
{
    
    // 标记字体
    CGFloat fontMarkTitle = 10;
    // 标记字左右间隙
    CGFloat marginMarkTitle = 4;
    /**
     PS: @3x
     注意 ：创建这个Label的时候，frame，font，cornerRadius要设置成所生成的图片的3倍，也就是说要生成一个三倍图，否则生成的图片会虚
     */
    CGFloat countQuanNX = 3;
    
    
    NSString *titleString = contentText;
    //创建  NSMutableAttributedString 富文本对象
    NSMutableAttributedString *maTitleString = [[NSMutableAttributedString alloc] initWithString:titleString];
    
    if (markTitle.length < 1) {
        
        return maTitleString;
    }
    
    //创建一个小标签的Label
    CGFloat lblW = fontMarkTitle*markTitle.length + marginMarkTitle * 2;
    
    
    UILabel *aaL = [UILabel new];
    aaL.frame = CGRectMake(0, 0, lblW*countQuanNX, 16*countQuanNX);
    aaL.text = markTitle;
    aaL.font = [UIFont boldSystemFontOfSize:fontMarkTitle*countQuanNX];
    aaL.textColor = [UIColor whiteColor];
    
    aaL.clipsToBounds = YES;
    aaL.layer.cornerRadius = 3*countQuanNX;
    aaL.textAlignment = NSTextAlignmentCenter;
    //调用方法，转化成Image
//    UIImage *image = [self imageWithUIView:aaL];
    
    // Save-start -------------------------------------------------------
    
    NSString * key = markTitle;
    UIImage * image = [[CPSCMarkAttributedStringTools shared].dictImage valueForKeyPath:key];
    if (!image) {
        image = [self imageWithUIView:aaL];
        [[CPSCMarkAttributedStringTools shared].dictImage setValue:image forKey:key];
    }
    // Save-end --------------------------------------------------------
    
    //创建Image的富文本格式
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.bounds = CGRectMake(0, -2.5, lblW+KValueImageMarginTitle, 16); //这个-2.5是为了调整下标签跟文字的位置
    attach.image = image;
    //添加到富文本对象里
    NSAttributedString * imageStr = [NSAttributedString attributedStringWithAttachment:attach];
    [maTitleString insertAttributedString:imageStr atIndex:0];//加入文字前面
    
    return maTitleString;
}


//view转成image
+ (UIImage*)imageWithUIView:(UIView*)view{
    
    /**
     PS: @3x
     注意 ：创建这个Label的时候，frame，font，cornerRadius要设置成所生成的图片的3倍，也就是说要生成一个三倍图，否则生成的图片会虚
     */
    CGFloat countQuanNX = 3;
    
    // ================================
    UIView * viewSuper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view.width + KValueImageMarginTitle, view.height)];
    viewSuper.backgroundColor= [UIColor whiteColor];
    UIView * viewSuperMark = [[UIView alloc] initWithFrame:CGRectMake(0, 0, view.width, view.height)];
    [viewSuper addSubview:viewSuperMark];
    
    //=======
//    viewSuper.backgroundColor = kCPSCRandomColor;
    
    // ================================================================
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;
    // 设置渐变颜色数组
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString:@"#ED6242"].CGColor,
                             (__bridge id)[UIColor colorWithHexString:@"#ED2929"].CGColor];
    // 设置渐变起始点
    gradientLayer.startPoint = CGPointMake(.0, .0);
    // 设置渐变结束点
    gradientLayer.endPoint = CGPointMake(.0, 1.0);
    gradientLayer.cornerRadius = 3*countQuanNX;
    
    // ================================================================
    viewSuperMark.layer.cornerRadius = 3*countQuanNX;
    [viewSuperMark.layer addSublayer:gradientLayer];
    [viewSuperMark addSubview:view];
    view.frame = viewSuperMark.bounds;
    view.backgroundColor = UIColor.clearColor;
    
    // ================================================================
    UIGraphicsBeginImageContext(viewSuper.bounds.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [viewSuper.layer renderInContext:ctx];
    UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tImage;
}

@end

